package org.example.myleet.p783;

import org.example.myleet.Utils.TreeNode;

public class Solution {
    /**
     * 0 ms
     * 栈迭代法遍历二叉搜索树
     */
    public int minDiffInBST(TreeNode root) {
        int lastElement = -100000;
        int minDiff = Integer.MAX_VALUE;
        int stackIdx = 0;
        TreeNode[] stack = new TreeNode[101];
        TreeNode node = root;
        while (node != null || stackIdx > 0) {
            while (node != null) {
                //一直将左边的节点入栈直到叶节点
                stack[stackIdx++] = node;
                node = node.left;
            }
            node = stack[--stackIdx];
            //计算刷新最小差值
            minDiff = Math.min(minDiff, node.val - lastElement);
            lastElement = node.val;
            //左子树和中节点已经遍历完成，接下来进入右子树做同样的操作直到完成遍历
            node = node.right;
        }
        return minDiff;
    }
}
